<template>
  <div class="page-container">
    <!-- 左侧收藏夹 -->
    <div class="favorites-sidebar">
      <h2>我的收藏 <span class="count">({{ favorites.length }})</span></h2>
      
      <div v-if="loadingFavorites" class="favorites-loading">
        <i class="el-icon-loading"></i> 加载收藏中...
      </div>
      
      <div v-else-if="favorites.length === 0" class="empty-favorites">
        <p>暂无收藏商品</p>
        <p>点击商品卡片上的"收藏"按钮添加</p>
      </div>
      
      <div v-else class="favorites-list">
        <div 
          v-for="item in favorites" 
          :key="item.id" 
          class="favorite-item"
          @click="goToProductDetail(item.id)"
        >
          <img 
            :src="`http://117.72.153.227/image/${item.fileName || ''}`" 
            :alt="item.productName"
            class="favorite-img"
          >
          <div class="favorite-info">
            <h4 class="favorite-name">{{ item.productName }}</h4>
            <p class="favorite-price">¥{{ item.price || 0.0 }}</p>
          </div>
          <button 
            class="remove-btn" 
            @click.stop="removeFavorite(item.id)"
          >
            <i class="el-icon-delete"></i>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 右侧商品列表区域 -->
    <div class="search-container">
      <!-- 当前分类信息 -->
      <div v-if="categoryPath.length > 0" class="search-info">
        <h2>
          <span
            v-for="(name, index) in categoryPath"
            :key="index"
            class="category-path"
          >
            {{ name }}
            <span v-if="index < categoryPath.length - 1" class="separator"
              >></span
            >
          </span>
        </h2>
        <div class="total-count">共找到 {{ pageInfo.total }} 件商品</div>
      </div>

      <div v-if="currentParams.productName" class="search-info">
        <h2>
          搜索关键词:
          <span class="highlight">{{ currentParams.productName }}</span>
        </h2>
        <div class="total-count">共找到 {{ pageInfo.total }} 件商品</div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-spinner">
        <i class="el-icon-loading"></i> 加载中...
      </div>
      
      <div v-else-if="pageInfo.total===0">
        <h1>
          查询不到您想要的商品哦，再逛逛别的吧
        </h1>
      </div>
      
      <!-- 商品列表 -->
      <div v-else class="product-list">
        <div
          v-for="product in products"
          :key="product.id"
          class="product-card"
          @click="goToProductDetail(product.id)"
        >
          <!-- 商品图片 -->
          <div class="product-image">
            <img
              :src="`http://117.72.153.227/image/${product.fileName || ''}`"
              :alt="product.productName"
            />
            <!-- 显示已收藏标记 -->
            <span v-if="isFavorite(product.id)" class="favorited-tag">
              <i class="el-icon-star-on"></i> 已收藏
            </span>
          </div>
          <!-- 商品信息 -->
          <div class="product-info">
            <h3 class="product-name" v-html="product.productName"></h3>
            <!-- 描述信息 -->
            <div class="description">
              商品描述:
              {{ product.description || "暂无描述" }}
            </div>
            <div class="description">
              价格:
              <span style="color: red">
                {{ product.price || 0.0 }}
              </span>
              元
            </div>
            
            <!-- 操作按钮：收藏和加入购物车 -->
            <div class="action-buttons">
              <button 
                class="collect-btn" 
                @click.stop="toggleCollect(product.id)"
              >
                <i :class="isFavorite(product.id) ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                {{ isFavorite(product.id) ? '取消收藏' : '收藏' }}
              </button>
              <button 
                class="cart-btn" 
                @click.stop="addToCart(product)"
              >
                <i class="el-icon-shopping-cart"></i> 加入购物车
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <el-pagination
        :current-page="Number(currentParams.pageNum)"
        :page-size="Number(currentParams.pageSize)"
        :total="pageInfo.total"
        @current-change="handlePageChange"
        layout="prev, pager, next"
        class="pagination"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "SearchProductView",
  data() {
    return {
      products: [], // 商品列表
      pageInfo: { total: 0 }, // 分页信息
      loading: false,
      currentParams: {},
      categoryPath: [],
      favorites: [], // 收藏商品列表
      loadingFavorites: false // 收藏加载状态
    };
  },
  methods: {
    parseRouteQuery(query = this.$route.query) {
      const {
        categoryId,
        subCategoryId,
        thirdCategoryId,
        pageNum,
        pageSize,
        productName,
      } = query;

      // 确保分页参数是数字类型
      this.currentParams = {
        pageNum: Number(pageNum) || 1,
        pageSize: Number(pageSize) || 8,
        productName, // 保留产品名称
        ...query,
      };

      // 确定分类等级和ID（仅在无productName时使用）
      if (!productName) {
        let level, id;
        if (thirdCategoryId) {
          level = 3;
          id = thirdCategoryId;
        } else if (subCategoryId) {
          level = 2;
          id = subCategoryId;
        } else if (categoryId) {
          level = 1;
          id = categoryId;
        }
        this.currentParams.level = level;
        this.currentParams.id = id;
      }

      // 加载分类路径
      if (query.categoryPath) {
        try {
          this.categoryPath = JSON.parse(query.categoryPath) || [];
        } catch (e) {
          console.error("解析分类路径失败:", e);
          this.categoryPath = [];
        }
      } else {
        this.categoryPath = [];
      }
    },
    async loadProducts() {
      this.loading = true;
      try {
        const params = {
          pageNum: Number(this.currentParams.pageNum),
          pageSize: Number(this.currentParams.pageSize),
        };

        // 优先使用产品名称搜索
        if (this.currentParams.productName) {
          params.productName = this.currentParams.productName;
        }
        // 如果没有产品名称，则使用分类搜索
        else if (this.currentParams.id) {
          switch (this.currentParams.level) {
            case 1:
              params.categoryLevel1Id = Number(this.currentParams.id);
              break;
            case 2:
              params.categoryLevel2Id = Number(this.currentParams.id);
              break;
            case 3:
              params.categoryLevel3Id = Number(this.currentParams.id);
              break;
          }
        } else {
          // 既没有产品名称也没有分类ID，可以显示所有商品或提示
          console.log("没有搜索条件");
        }

        const response = await axios.get("/api/product/searchProduct", {
          params,
        });
        this.pageInfo = response.data.pageInfo;
        this.products = response.data.pageInfo.list;
      } catch (error) {
        console.error("查询商品失败:", error);
      } finally {
        this.loading = false;
      }
    },
    
    // 获取用户收藏的商品
    async loadFavorites() {
      const token = sessionStorage.getItem("token");
      if (!token) {
        this.favorites = [];
        return;
      }
      
      this.loadingFavorites = true;
      try {
        const response = await axios.get("/api/product/getFavoriteList");
        
        if (response.data.code === 200) {
          this.favorites = response.data.list || [];
        } else {
          console.error("获取收藏失败:", response.data.msg);
          this.favorites = [];
        }
      } catch (error) {
        console.error("获取收藏失败:", error);
        this.favorites = [];
      } finally {
        this.loadingFavorites = false;
      }
    },
    
    // 判断商品是否已收藏
    isFavorite(productId) {
      return this.favorites.some(item => item.id === productId);
    },
    
    // 移除收藏
    async removeFavorite(productId) {
      const token = sessionStorage.getItem("token");
      if (!token) {
        this.$message.error("用户未登录");
        return;
      }
      
      try {
        const response = await axios.delete(
          `/api/product/deleteFavorite/${productId}`
        );
        
        if (response.data.code === 200) {
          this.$message.success("已取消收藏");
          // 重新加载收藏列表
          this.loadFavorites();
        } else {
          this.$message.error(response.data.msg || "取消收藏失败");
        }
      } catch (error) {
        console.error("取消收藏失败:", error);
        this.$message.error("取消收藏操作失败");
      }
    },

    handlePageChange(page) {
      this.$router.push({
        query: {
          ...this.$route.query,
          pageNum: page,
        },
      });
    },

    // 跳转到商品详情页
    goToProductDetail(productId) {
      this.$router.push(`/ShowProduct/${productId}`);
    },

    // 收藏/取消收藏商品
    async toggleCollect(productId) {
      const token = sessionStorage.getItem("token");
      if (!token) {
        this.$message.error("用户未登录");
        return;
      }
      
      // 如果已经收藏，则执行取消收藏
      if (this.isFavorite(productId)) {
        return this.removeFavorite(productId);
      }
      
      try {
        const response = await axios.post(
          `/api/product/addFavorite/${productId}`,
          {},
          {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }
        );
        
        console.log(response);
        if (response.data.code === '400' || response.data.code === '401') {
          this.$message.error(response.data.msg);
        } else if (response.data.code === 5001) {
          this.$message.error("添加失败");
        } else {
          this.$message.success("收藏添加成功");
          // 重新加载收藏列表
          this.loadFavorites();
        }
      } catch (error) {
        console.error("收藏失败:", error);
        this.$message.error("收藏操作失败");
      }
    },

    // 加入购物车
    async addToCart(product) {
      try {
        const token = sessionStorage.getItem("token");
        if (!token) {
          this.$message.error("用户未登录");
          return;
        }

        const payload = {
          productId: Number(product.id),
          productName: product.productName,
          price: Number(product.price),
          quantity: 1, // 默认添加1个
          fileName: product.fileName,
          cost: Number(product.price * 1),
        };

        // 发送请求
        const response = await axios.post(
          `/api/shoppingCart/addProductToCart`,
          payload,
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
          }
        );

        // 处理响应
        if (response.data.code === 200) {
          this.$message.success("添加成功");
            // 重新获取最新购物车
          await this.$store.dispatch("fetchCart");
        }
      } catch (error) {
        console.error("添加购物车失败:", {
          error: error.response?.data || error.message,
          request: error.config,
        });
        this.$message.error(error.response?.data?.message || "添加失败");
      }
    },
  },
  created() {
    this.parseRouteQuery(); //初始化 currentParams
    this.loadProducts(); //基于 currentParams 
    this.loadFavorites(); // 加载收藏商品
  },
  watch: {
    "$route.query"(query) {
      this.parseRouteQuery(query);
      this.loadProducts();
    },
    // 监听token变化，重新加载收藏
    "$sessionStorage.token": function() {
      this.loadFavorites();
    }
  },
};
</script>

<style scoped>
/* 页面整体布局 */
.page-container {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

/* 左侧收藏夹样式 */
.favorites-sidebar {
  width: 300px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 15px;
  height: fit-content;
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.favorites-sidebar h2 {
  font-size: 18px;
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.count {
  color: #6495ED;
  font-size: 14px;
  font-weight: normal;
}

.favorites-loading {
  text-align: center;
  padding: 30px 0;
  color: #666;
}

.empty-favorites {
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

.empty-favorites p {
  margin: 5px 0;
}

.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.favorite-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 4px;
  background: #f9f9f9;
  cursor: pointer;
  transition: background-color 0.2s;
}

.favorite-item:hover {
  background: #f0f0f0;
}

.favorite-img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.favorite-info {
  flex: 1;
  min-width: 0;
}

.favorite-name {
  font-size: 14px;
  margin: 0 0 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.favorite-price {
  font-size: 14px;
  color: #e4393c;
  margin: 0;
}

.remove-btn {
  width: 30px;
  height: 30px;
  border: none;
  background: transparent;
  color: #999;
  cursor: pointer;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.remove-btn:hover {
  background: #ffeeee;
  color: #e4393c;
}

/* 右侧商品列表区域样式 */
.search-container {
  flex: 1;
}

/* 分类信息 */
.search-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 4px;
}
.highlight {
  color: #e4393c;
  font-weight: bold;
}
.total-count {
  color: #666;
  margin-top: 5px;
}

/* 商品列表 */
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

/* 商品卡片 */
.product-card {
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}
.product-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

/* 商品图片 */
.product-image {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
  margin: 0 auto; /* 图片居中 */
}
.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 已收藏标记 */
.favorited-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(228, 57, 60, 0.8);
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.category-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 商品信息区域 */
.product-info {
  padding: 15px;
}
.product-name {
  font-size: 16px;
  margin: 0 0 10px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.description {
  font-size: 13px;
  color: #666;
  margin-top: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}
.collect-btn, .cart-btn {
  flex: 1;
  padding: 8px 0;
  border: none;
  border-radius: 4px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}
.collect-btn {
  background-color: #6495ED;
}
.collect-btn:hover {
  background-color: #4169E1;
}
/* 已收藏按钮样式 */
.collect-btn .el-icon-star-on {
  color: #FFD700;
}

.cart-btn {
  background-color: #FF6347;
}
.cart-btn:hover {
  background-color: #CD5C5C;
}

/* 加载状态 */
.loading-spinner {
  text-align: center;
  padding: 50px 0;
  color: #666;
}
.el-icon-loading {
  font-size: 24px;
  margin-right: 10px;
}

/* 分页 */
.pagination {
  margin: 30px 0;
  text-align: center;
}

</style>
    